package com.diudiutechnology.www.yadiudiu.yadiudiu.car.MyActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.clusterutil.clustering.Cluster;
import com.diudiutechnology.www.yadiudiu.util.utils.clusterutil.clustering.ClusterItem;
import com.diudiutechnology.www.yadiudiu.util.utils.clusterutil.clustering.ClusterManager;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.BuyAcarModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;


import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/9/8.
 * 洗车地图
 */

public class WashTheCarMapActivity extends Activity implements View.OnClickListener, BaiduMap.OnMapLoadedCallback {
    @Bind(R.id.retur)
    LinearLayout retur;
    Context context;
    private MyProgressDialog mDialog;
    @Bind(R.id.bmapsView)//地图
            MapView mMapView;
    BaiduMap mBaiduMap;
    MapStatus ms;
    BitmapDescriptor mCurrentMarker;
    private ClusterManager<MyItem> mClusterManager;
    List<BuyAcarModel> washTheCarMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_wash_the_car_map);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        LatLng latLng = new LatLng(MyApplication.getInstance().getLatitude(), MyApplication.getInstance().getLongitude());
       ms = new MapStatus.Builder().target(latLng).zoom(8).build();
        mBaiduMap = mMapView.getMap();
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.mipmap.label_delete);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(latLng)
                .icon(mCurrentMarker);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
        mBaiduMap.setOnMapLoadedCallback(this);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
        // 定义点聚合管理类ClusterManager
        mClusterManager = new ClusterManager<>(this, mBaiduMap);
        // 添加Marker点
        processadd();
        // 设置地图监听，当地图状态发生改变时，进行点聚合运算
        mBaiduMap.setOnMapStatusChangeListener(mClusterManager);
        // 设置maker点击时的响应
        mBaiduMap.setOnMarkerClickListener(mClusterManager);

        mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<MyItem>() {
            @Override
            public boolean onClusterClick(Cluster<MyItem> cluster) {
                Toast.makeText(WashTheCarMapActivity.this,
                        "有" + cluster.getSize() + "个点", Toast.LENGTH_SHORT).show();

                return false;
            }
        });
        mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
            @Override
            public boolean onClusterItemClick(MyItem item) {
                Toast.makeText(WashTheCarMapActivity.this,
                        "点击单个Item", Toast.LENGTH_SHORT).show();

                return false;
            }
        });

    }

    /**
     * 向地图添加Marker点
     */
    public void addMarkers() {
        List<MyItem> items = new ArrayList<>();

        for (int i = 0; i < washTheCarMap.size(); i++) {
            BuyAcarModel buyAcarModel = washTheCarMap.get(i);
            if (!Sundry.getStinges(buyAcarModel.getLongitude())) {
                Double longitude = Double.valueOf(buyAcarModel.getLongitude());
                Double latitude = Double.valueOf(buyAcarModel.getLatitude());
                LatLng llA= new LatLng(latitude, longitude);
                items.add(new MyItem(llA));
            }
        }
        mClusterManager.addItems(items);
        ms = new MapStatus.Builder().zoom(13).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }

    //获取洗车
    private void processadd() {
        if (Sundry.isOpenNetwork(context)) {
            mDialog = new MyProgressDialog(context);
            HttpClient.graticules(MyApplication.getInstance().getLongitude() + "", MyApplication.getInstance().getLatitude() + "", new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    System.out.println("stringmd5" + result);

                    List<MerchantsTypeModel> getmerchanttype = JsonTools.getmerchanttype(result);
                    if (getmerchanttype != null || getmerchanttype.size() > 0) {
                        String error = getmerchanttype.get(0).getError();
                        String mssage = getmerchanttype.get(0).getMssage();
                        if (error.equals("200")) {
                            String result1 = getmerchanttype.get(0).getResult();
                            washTheCarMap = JsonTools.getWashTheCarMap(result1);
                            if (washTheCarMap != null || washTheCarMap.size() > 0) {
                                addMarkers();
                            }


                        } else if (error.equals("105")) {
                            Intent intent = new Intent(context, LoginActivity.class);
                            startActivity(intent);
                            ToastUtils.show(context, mssage);
                        } else {
                            ToastUtils.show(context, mssage);
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    ToastUtils.Toastshow(context, getResources().getString(R.string.server));
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    ToastUtils.Toastshow(context, getResources().getString(R.string.server));
                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }


    @Override
    public void onClick(View view) {
        finish();
    }

    /**
     * 每个Marker点，包含Marker点坐标以及图标
     */
    public class MyItem implements ClusterItem {
        private final LatLng mPosition;

        public MyItem(LatLng latLng) {
            mPosition = latLng;
        }

        @Override
        public LatLng getPosition() {
            return mPosition;
        }

        @Override
        public BitmapDescriptor getBitmapDescriptor() {
            return BitmapDescriptorFactory
                    .fromResource(R.mipmap.icon_gcoding);
        }
    }

    @Override
    public void onMapLoaded() {
        // TODO Auto-generated method stub
        ms = new MapStatus.Builder().zoom(9).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }



}
